package com.example.demojenkins.controller;

import com.example.demojenkins.dto.MenusDto;
import com.example.demojenkins.entity.Menu;
import com.example.demojenkins.entity.TableData;
import com.example.demojenkins.entity.TblOrderInfo;
import com.example.demojenkins.service.MenuService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * (Menu)表控制层
 *
 * @author makejava
 * @since 2024-08-24 18:16:59
 */
@RestController
@RequestMapping("/menu")
public class MenuController {
    /**
     * 服务对象
     */
    @Autowired
    private MenuService menuService;

    /**
     * 分页查询
     *
     * @param menu 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @GetMapping
    public ResponseEntity<Page<Menu>> queryByPage(Menu menu, PageRequest pageRequest) {
        return ResponseEntity.ok(this.menuService.queryByPage(menu, pageRequest));
    }

    @PreAuthorize("hasAnyAuthority('text','admin')")
    @GetMapping("/findAll")
    public ResponseEntity<List<Menu>> findAll() {
        List<Menu> allMenus = menuService.findAllMenus();
        //一级菜单
        List<Menu> collect = allMenus.stream().filter(menu -> menu.getParentId() == null)
                .collect(Collectors.toList());
        for (Menu menu : collect) {
            menu.setChildren(allMenus.stream().filter(m -> menu.getMenuId() .equals(m.getParentId()))
                    .collect(Collectors.toList()));
        }

        return ResponseEntity.ok(collect);
    }

    @PreAuthorize("hasAnyAuthority('text','admin')")
    @PostMapping(value = "/list")
    public Map<String, Object> queryByPage2(@RequestBody TableData tableData) {
        Integer page = tableData.getPageNum();
        Integer size = tableData.getPageSize();
        if (page != null) {
            page = (page - 1) * size;
        }
        Menu menu = new Menu();
        Long count = menuService.count(menu);
        List<Menu> menus = menuService.queryByPage2(page, size);
        Map<String, Object> map = new HashMap<>();
        map.put("total", count);
        map.put("data", menus);
        return map;
    }

    /**
     * 通过主键查询单条数据
     *
     * @param id 主键
     * @return 单条数据
     */
    @GetMapping("{id}")
    public ResponseEntity<Menu> queryById(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(this.menuService.queryById(id));
    }

    /**
     * 新增数据
     *
     * @param menu 实体
     * @return 新增结果
     */
    @PreAuthorize("hasAnyAuthority('text','admin')")
    @PostMapping("/save")
    public ResponseEntity<Menu> add(@RequestBody Menu menu) {
        System.out.println(menu);
        return ResponseEntity.ok(this.menuService.insert(menu));
    }

    /**
     * 编辑数据
     *
     * @return 编辑结果
     */
    @PreAuthorize("hasAnyAuthority('text','admin')")
    @GetMapping("/getBackgroundRouter/{userName}")
    public ResponseEntity<Map<String , Object>> edit(@PathVariable("userName") String userName) {
        System.out.println(userName);
        //根据用户名查询出角色
        List<Menu> menus = menuService.queryByUserName(userName);
        //将父节点为空的数据筛掉
        List<Menu> sidebar = menus.stream().filter(menu -> menu.getParentId() != null).collect(Collectors.toList());
        List<MenusDto> menusDtos = new ArrayList<>();
        for (Menu menu : menus) {
            if (menu.getParentId() == null) {
                MenusDto menusDto = new MenusDto();
                menusDto.setMenuId(menu.getMenuId());
                menusDto.setMenuName(menu.getMenuName());
                menusDtos.add(menusDto);
            }
        }

        for (MenusDto menusDto : menusDtos) {
            List<Menu> children = new ArrayList<>();
            for (Menu menu : sidebar) {
                if (menu.getParentId().equals(menusDto.getMenuId())) {
                    children.add(menu);
                    menusDto.setChildren(children);
                }

            }
        }
        HashMap<String, Object> map = new HashMap<>();
        map.put("backgroundRouter",sidebar );
        map.put("sidebar", menusDtos);
        System.out.println(map);
        return ResponseEntity.ok(map);
    }

    /**
     * 删除数据
     *
     * @param
     * @return 删除是否成功
     */
    @DeleteMapping("/{ids}")
    public ResponseEntity<Boolean> deleteById(@PathVariable List<Integer> ids) {
        return ResponseEntity.ok(this.menuService.deleteByIds(ids));
    }


    @PreAuthorize("hasAnyAuthority('text','admin')")
    @PostMapping("update")
    public ResponseEntity<Menu> getBackgroundRouter(@RequestBody Menu menu) {
        System.out.println(menu);
        return ResponseEntity.ok(this.menuService.update(menu));
    }

}

